package com.bii.gelapp;

import java.io.ByteArrayOutputStream;
import java.util.ArrayList;

import org.opencv.android.Utils;
import org.opencv.core.Core;
import org.opencv.core.CvType;
import org.opencv.core.Mat;
import org.opencv.core.Point;
import org.opencv.core.Scalar;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;

public class CalculateActivity extends Activity {
	ImageView ivImage;
	Button btCalculate, btPrev, btGraph;
	Bitmap colorBmp;

	ArrayList<ConnectedComponent> componentlist = new ArrayList<ConnectedComponent>();
	ArrayList<ConnectedComponent> markerlist = new ArrayList<ConnectedComponent>();
	ArrayList componentvalues = new ArrayList();

	Bitmap bmap;
	Mat drawmat;

	MarkerStandard mss;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.calculateactivity);
		ivImage = (ImageView) findViewById(R.id.ivImage);
		byte[] byteArray = getIntent().getByteArrayExtra("BMP");
		colorBmp = BitmapFactory
				.decodeByteArray(byteArray, 0, byteArray.length);
		componentlist = (ArrayList<ConnectedComponent>) getIntent()
				.getSerializableExtra("componentlist");
		markerlist = (ArrayList<ConnectedComponent>) getIntent()
				.getSerializableExtra("markerlist");

		mss = StartActivity.ms;

		bmap = colorBmp;
		drawmat = new Mat(bmap.getHeight(), bmap.getWidth(), CvType.CV_8U);

		drawRectangles();
		Bitmap drawnbmp = Bitmap.createBitmap(drawmat.cols(), drawmat.rows(),
				Bitmap.Config.RGB_565);
		Utils.matToBitmap(drawmat, drawnbmp);

		Bitmap resizedbmp = Bitmap.createScaledBitmap(drawnbmp, 300, 300, true);
		ivImage.setImageBitmap(resizedbmp);

		btCalculate = (Button) findViewById(R.id.btCalculate);
		btCalculate.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				for (int i = 0; i < componentlist.size(); i++) {
					getValuesOfComponent(componentlist.get(i));
				}
				// component values
				for (int i = 0; i < componentlist.size(); i++) {
					int top = componentlist.get(i).top;
					int bottom = componentlist.get(i).bottom;
					int left = componentlist.get(i).left;
					int right = componentlist.get(i).right;

					// int centerheight = (bottom + top)/2;
					int centerheight = bottom;
					int centerwidth = (right + left) / 2;
					Point org = new Point(centerwidth, centerheight);

					float value = (Float) componentvalues.get(i);

					// String valuedisplay = " "+ value;
					String valuedisplay = String.format("%.2f", value);
					Core.putText(drawmat, valuedisplay, org, 3, 1, new Scalar(
							255, 0, 0), 3);

				}
				// marker values
				for (int i = 0; i < markerlist.size(); i++) {
					;
					int top = markerlist.get(i).top;
					int bottom = markerlist.get(i).bottom;
					int left = markerlist.get(i).left;
					int right = markerlist.get(i).right;

					int centerheight = (bottom + top) / 2;
					int centerwidth = (right + left) / 2;
					Point org = new Point(centerwidth, centerheight);

					MarkerConnectedComponent mcc = mss.getmarkers().get(i);
					int value = mcc.value;
					String valuedisplay = " " + value;
					int[] msscolors = mss.getmarkers().get(i).color;
					int red = msscolors[0];
					int green = msscolors[1];
					int blue = msscolors[2];

					Core.putText(drawmat, valuedisplay, org, 3, 1, new Scalar(
							red, green, blue), 5);
					Bitmap drawnbmp = Bitmap.createBitmap(drawmat.cols(),
							drawmat.rows(), Bitmap.Config.RGB_565);
					Utils.matToBitmap(drawmat, drawnbmp);

					Bitmap resizedbmp = Bitmap.createScaledBitmap(drawnbmp,
							300, 300, true);
					ivImage.setImageBitmap(resizedbmp);

				}

				Bitmap drawnbmp = Bitmap.createBitmap(drawmat.cols(),
						drawmat.rows(), Bitmap.Config.RGB_565);
				Utils.matToBitmap(drawmat, drawnbmp);

				Bitmap resizedbmp = Bitmap.createScaledBitmap(drawnbmp, 300,
						300, true);
				ivImage.setImageBitmap(resizedbmp);
			}

		});

		ivImage.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent goToNextActivity = new Intent(getApplicationContext(),
						CalculateFullscreenActivity.class);
				// Intent goToNextActivity = new Intent(getApplicationContext(),
				// CalculateActivity.class);
				byte[] bytes;
				bytes = compressImage(colorBmp);
				goToNextActivity.putExtra("BMP", bytes);
				goToNextActivity.putExtra("componentlist", componentlist);
				goToNextActivity.putExtra("markerlist", markerlist);
				startActivity(goToNextActivity);

			}
		});

	}

	private void getValuesOfComponent(ConnectedComponent cc) {
		ConnectedComponent cctop;
		ConnectedComponent ccbottom;
		int topindex = 0;
		int bottomindex = 1;
		float comparedifferencetop = 9999;
		float comparedifferencebottom = 9999;

		int cccenterheight = (cc.top + cc.bottom) / 2;

		for (int j = 0; j < markerlist.size(); j++) {
			if (j + 1 != markerlist.size()) {
				float comparetopcenter = (markerlist.get(j).top + markerlist
						.get(j).bottom) / 2;
				float comparebottomcenter = (markerlist.get(j + 1).top + markerlist
						.get(j + 1).bottom) / 2;
				if (comparedifferencetop == 9999
						&& comparedifferencebottom == 9999) {

					comparedifferencetop = Math.abs(cccenterheight
							- comparetopcenter);
					comparedifferencebottom = Math.abs(cccenterheight
							- comparebottomcenter);

					// comparedifferencetop = cccenterheight - comparetopcenter;
					// comparedifferencebottom = cccenterheight -
					// comparebottomcenter;
					cctop = markerlist.get(j);
					ccbottom = markerlist.get(j + 1);
					topindex = j;
					bottomindex = j + 1;
				} else {
					if (cccenterheight > comparetopcenter
							&& cccenterheight < comparebottomcenter) {
						float differencetop = Math.abs(cccenterheight
								- comparetopcenter);
						float differencebottom = Math.abs(cccenterheight
								- comparebottomcenter);

						// float differencetop = cccenterheight -
						// comparetopcenter;
						// float differencebottom = cccenterheight -
						// comparebottomcenter;

						if (differencetop < comparedifferencetop
								&& differencebottom < comparedifferencebottom) {
							comparedifferencetop = differencetop;
							comparedifferencebottom = differencebottom;
							cctop = markerlist.get(j);
							ccbottom = markerlist.get(j + 1);
							topindex = j;
							bottomindex = j + 1;
						} else {
							;
						}
					} else {
						;
					}
				}

			}
		}
		/*
		 * // MarkerConnectedComponent mcc =
		 * mss.getmarkers().get(i+lowestindex); MarkerConnectedComponent mcctop
		 * = mss.getmarkers().get(topindex); MarkerConnectedComponent mccbottom
		 * = mss.getmarkers().get(bottomindex); float topvalue = mcctop.value;
		 * float bottomvalue = mccbottom.value;
		 * 
		 * float power = 0;
		 * 
		 * float powerleft = (float) Math.log10(bottomvalue); float
		 * powerrightone = (float) (Math.log10(topvalue) - Math
		 * .log10(bottomvalue)); float powerrighttwo = comparedifferencebottom;
		 * //float powerrightthree = comparedifferencetop;
		 * 
		 * float comparetopcenter = (markerlist.get(topindex).top + markerlist
		 * .get(topindex).bottom) / 2; float comparebottomcenter =
		 * (markerlist.get(bottomindex).top + markerlist
		 * .get(bottomindex).bottom) / 2;
		 * 
		 * float powerrightthree = Math.abs(comparetopcenter -
		 * comparebottomcenter); // float powerright = powerrightone *
		 * (powerrighttwo / powerrightthree); float powerright = (powerrightone
		 * * powerrighttwo) / powerrightthree;
		 * 
		 * power = powerleft + powerright;
		 * 
		 * float ccvalue = (float) Math.pow(10, power); Log.d("tag1",
		 * "ccvalue: " + ccvalue); componentvalues.add(ccvalue);
		 */
		// MarkerConnectedComponent mcc = mss.getmarkers().get(i+lowestindex);
		MarkerConnectedComponent mcctop = mss.getmarkers().get(topindex);
		MarkerConnectedComponent mccbottom = mss.getmarkers().get(bottomindex);
		float topvalue = mcctop.value;
		float bottomvalue = mccbottom.value;

		float power = 0;

		float powerleft = (float) Math.log10(bottomvalue);
		float powerrightone = (float) (Math.log10(topvalue) - Math
				.log10(bottomvalue));
		float powerrighttwo = comparedifferencebottom;
		// float powerrightthree = comparedifferencetop;
		float comparetopcenter = (markerlist.get(topindex).top + markerlist
				.get(topindex).bottom) / 2;
		float comparebottomcenter = (markerlist.get(bottomindex).top + markerlist
				.get(bottomindex).bottom) / 2;

		float powerrightthree = Math
				.abs(comparetopcenter - comparebottomcenter);
		// float powerright = powerrightone * (powerrighttwo / powerrightthree);
		float powerright = powerrightone * (powerrighttwo / powerrightthree);

		power = powerleft + powerright;

		float ccvalue = (float) Math.pow(10, power);
		Log.d("tag1", "ccvalue: " + ccvalue);
		componentvalues.add(ccvalue);
	}

	private void drawRectangles() {
		Utils.bitmapToMat(bmap, drawmat);
		for (int i = 0; i < componentlist.size(); i++) {
			Core.rectangle(drawmat, new Point(componentlist.get(i).left,
					componentlist.get(i).top), new Point(
					componentlist.get(i).right, componentlist.get(i).bottom),
					new Scalar(255, 0, 0), 2);
			// 11/8
			int top = componentlist.get(i).top;
			int bottom = componentlist.get(i).bottom;
			int left = componentlist.get(i).left;
			int right = componentlist.get(i).right;

			int centerheight = (bottom + top) / 2;
			int centerwidth = (right + left) / 2;
			Point org = new Point(centerwidth, centerheight);

			Core.putText(drawmat, "" + i, org, 3, 1, new Scalar(0, 0, 255), 5);
			// Core.putText(img, text, org, fontFace, fontScale, color);
		}
		for (int i = 0; i < markerlist.size(); i++) {
			Core.rectangle(drawmat, new Point(markerlist.get(i).left,
					markerlist.get(i).top), new Point(markerlist.get(i).right,
					markerlist.get(i).bottom), new Scalar(255, 255, 0), 2);
			int top = markerlist.get(i).top;
			int bottom = markerlist.get(i).bottom;
			int left = markerlist.get(i).left;
			int right = markerlist.get(i).right;

			int centerheight = (bottom + top) / 2;
			Point org = new Point(right, centerheight);

			Core.putText(drawmat, "" + i, org, 3, 1, new Scalar(0, 255, 0), 5);
		}
		Bitmap drawnbmp = Bitmap.createBitmap(drawmat.cols(), drawmat.rows(),
				Bitmap.Config.RGB_565);
		Utils.matToBitmap(drawmat, drawnbmp);

		Bitmap resizedbmp = Bitmap.createScaledBitmap(drawnbmp, 300, 300, true);
		ivImage.setImageBitmap(resizedbmp);

	};

	public byte[] compressImage(Bitmap image) {
		ByteArrayOutputStream stream = new ByteArrayOutputStream();
		image.compress(Bitmap.CompressFormat.PNG, 0, stream);
		byte[] bytes = stream.toByteArray();
		return bytes;
	}
}
